package xyz.shenmegui.foodcheckserver.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.shenmegui.foodcheckserver.DO.SysConfig;
import xyz.shenmegui.foodcheckserver.DO.User;
import xyz.shenmegui.foodcheckserver.VO.WxLoginForm;
import xyz.shenmegui.foodcheckserver.mapper.UserMapper;
import xyz.shenmegui.foodcheckserver.service.SysConfigService;
import xyz.shenmegui.foodcheckserver.service.UserService;
import xyz.shenmegui.foodcheckserver.http.HttpRequest;
import xyz.shenmegui.foodcheckserver.utils.ObjectUtil;

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    SysConfigService sysConfigService;

    @Override
    public User getUserInfo(User user) {
        return user;
    }

    @Override
    public User getUserById(int id) {
        return userMapper.selectById(id);
    }

    @Override
    public Integer updateUserInfo(User user) {
        return userMapper.updateById(user);
    }

    @Override
    public Integer wxLogin(WxLoginForm form) {
        String openid = getOpenId(form.getCode());
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("openid", openid));
        if (ObjectUtil.isNotNull(user)) {
            return user.getId();
        } else {
            User user1 = new User();
            user1.setAvatar(form.getAvatar());
            user1.setUsername(form.getUsername());
            user1.setOpenid(openid);
            userMapper.insert(user1);
            return user1.getId();
        }
    }

    @Override
    public String getOpenId(String code) {
        SysConfig system = sysConfigService.getConfig("wx");
        //小程序唯一标识   (在微信小程序管理后台获取)
        String appId = system.getValue();
        //小程序的 app secret (在微信小程序管理后台获取)
        String secret = system.getExtra();
        //授权（必填）
        String grant_type = "authorization_code";
        //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        //向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        String params = "appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相应内容（转换成json对象）
        JSONObject json = JSON.parseObject(sr);
        System.out.println((String) json.get("openid"));
        //用户的唯一标识（openId）
        return (String) json.get("openid");
    }
}
